﻿using Dapper;
using Gx.Common.Core;
using Gx.Model.Entity;
using Gx.Model.ViewModel;
using System.Collections.Generic;
using System.Linq;
namespace Gx.Dal.Manage
{
    public class LKCompanyDal:BaseDal<LKCompany>
    {
    
        /// <summary>
        /// 名称是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool AnyName(string name)
        {
            using (var conn = new DbContext())
            {
                var total = conn.Connection.QueryFirst<int>("SELECT COUNT(1) FROM LK_Company WITH(NOLOCK) WHERE IsDeleted=0 AND CompanyName=@name", new { name });
                return total > 0;
            }
        }
        
        /// <summary>
        /// 获取最大编号
        /// </summary>
        /// <returns></returns>
        public string GetMaxLKCompanyCode()
        {
            using (var conn = new DbContext())
            {
                return conn.Connection.QueryFirst<string>("SELECT MAX(CompanyCode) FROM LK_Company WITH(NOLOCK)");
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedList<LKCompany> GetLKCompanyPageList(LKCompanyInput input)
        {
            string sql = "SELECT * FROM LK_Company WITH(NOLOCK) WHERE IsDeleted=0 @WHERE";
            List<string> conditions = new List<string>();
            //判断input的属性是否为空，如果不为空则添加到conditions中

            if (!string.IsNullOrWhiteSpace(input.Company))
            {
                input.Company = $"%{input.Company}%";
                conditions.Add("(CompanyName LIKE @Company OR CompanyCode LIKE @Company)");
            }
            string condition = string.Empty;
            if (conditions.Any())
            {
                condition = $" AND {string.Join(" AND ", conditions)}";
            }
            sql = !string.IsNullOrWhiteSpace(condition) ? sql.Replace("@WHERE", condition) : sql.Replace("@WHERE", "");

            using (var conn = new DbContext())
            {
                return conn.Connection.GetPagedList<LKCompany>(sql, "CreateTime Desc", input);
            }
        }
    }
}

